const PENDING = "pending" // 等待
const FULFILLED = "fulfulled" // 成功
const REJECTED = "rejected" // 失败

class myPromise {
    constructor(executor) {
        try {
            executor(this.resolve,this.reject)
        } catch (error) {
            this.reject(error)
        }
    }
    // promise 状态
    status = PENDING
    // 成功后的值
    value = undefined
    // 失败后的原因
    reason = undefined
    // 成功回调
    successCallBack = []
    // 失败回调
    failCallBack = []

    resolve = (value) => {
        // 如果程序不是等待，阻止向下执行
        if (this.status !== PENDING) return 
        // 更改状态为成功
        this.status = FULFILLED
        // 传递成功后的值
        this.value = value
        // 判断是否存在成功回调, 循环调用
        // this.successCallBack && this.successCallBack(this.value)
        while(this.successCallBack.length) {
            this.successCallBack.shift()()
        }
    }
    reject = (reason) => {
        // 如果程序不是等待，阻止向下执行
        if (this.status !== PENDING) return 
        // 更改状态为失败
        this.status = REJECTED
        // 传递失败后的原因
        this.reason = reason
        // 判断是否存在失败回调, 循环调用
        // this.failCallBack && this.failCallBack(this.value)
        while(this.failCallBack.length) {
            this.failCallBack.shift()()
        }
    }
    then(successCallback, failCallBack) {
        successCallback = successCallback ? successCallback : value => value
        failCallBack = failCallBack ? failCallBack : reason => {throw reason}
        let promise2 = new myPromise((resolve, reject) => {
            // 判断状态
            if(this.status === FULFILLED) {
                // 调用成功回调
                setTimeout(() => {
                    try {
                        let x = successCallback(this.value)
                        // 判断当前x 值是否为普通值还是promise对象
                        // 如果是普通纸， 直接resolve
                        // 如果是promise 对象， 查看promise对象的返回结果
                        // 再根据promise对象返回的结果决定调用resolve还是reject
                        resolvePromise(promise2, x, resolve, reject)
                    } catch (error) {
                        reject(error)
                    }
                }, 0);
            } else if (this.status === REJECTED) {
                // 调用失败回调
                setTimeout(() => {
                    try {
                        let x = failCallBack(this.reason)
                        // 判断当前x 值是否为普通值还是promise对象
                        // 如果是普通纸， 直接resolve
                        // 如果是promise 对象， 查看promise对象的返回结果
                        // 再根据promise对象返回的结果决定调用resolve还是reject
                        resolvePromise(promise2, x, resolve, reject)
                    } catch (error) {
                        reject(error)
                    }
                }, 0);
            } else {
                // 等待状态
                // 将成功和失败回调存储下来
                this.successCallBack.push(() => {
                    // 调用成功回调
                    setTimeout(() => {
                        try {
                            let x = successCallback(this.value)
                            // 判断当前x 值是否为普通值还是promise对象
                            // 如果是普通纸， 直接resolve
                            // 如果是promise 对象， 查看promise对象的返回结果
                            // 再根据promise对象返回的结果决定调用resolve还是reject
                            resolvePromise(promise2, x, resolve, reject)
                        } catch (error) {
                            reject(error)
                        }
                    }, 0);
                })
                this.failCallBack.push(() => {
                    // 调用失败回调
                    setTimeout(() => {
                        try {
                            let x = failCallBack(this.reason)
                            // 判断当前x 值是否为普通值还是promise对象
                            // 如果是普通纸， 直接resolve
                            // 如果是promise 对象， 查看promise对象的返回结果
                            // 再根据promise对象返回的结果决定调用resolve还是reject
                            resolvePromise(promise2, x, resolve, reject)
                        } catch (error) {
                            reject(error)
                        }
                    }, 0);
                })
            }
        })
        return promise2
    }
    catch(callback) {
        return this.then(undefined, callback)
    }
    finally(callback) {
        return this.then((val) => {
            return myPromise.resolve(callback()).then(() => val)
        }, (reason) => {
            return myPromise.resolve(callback()).then(() => {throw reason})
        })
    }
    static all (array) {
        let result = []
        let index = 0
        return new myPromise((resolve, reject) => {
            function addData(key, value) {
                index++
                result[key] = value
                if (index === array.length) {
                    resolve(result)
                }
            }
            for(let i = 0; i < array.length; i++) {
                let cur = array[i]
                if (cur instanceof myPromise) {
                    // promise
                    cur.then(val => addData(i, val), reason => reject(reason))
                } else {
                    // 普通值
                    addData(i, array[i])
                }
            }
            // resolve(result)
        }) 
    }
    static resolve(value) {
        if (value instanceof myPromise) return value
        return new myPromise(resolve => resolve(value))
    }
}

function resolvePromise(promise2, x, resolve, reject) {
    if (x === promise2) {
        return reject(new TypeError("Chaining cycle detected for promise #<Promise>"))
    }
    if(x instanceof myPromise) {
        x.then(resolve, reject)
    } else {
        // 普通纸
        resolve(x)
    }
}

module.exports = myPromise